/*
 *  Copyright 2019-2020 Zheng Jie
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package me.zhengjie.modules.power.utilVideo;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 视频流传输WebSocket
 */
@Slf4j
//@Component
//@ServerEndpoint("/VideoStreamWebSocket/{cameraId}")
public class VideoStreamWebSocket {
    /**
     * 记录当前在线连接数
     */
    private static final AtomicInteger onlineCount = new AtomicInteger(0);
    /**
     * concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
     */
    private static final CopyOnWriteArraySet<VideoStreamWebSocket> videoStreamWebSocketSet = new CopyOnWriteArraySet<VideoStreamWebSocket>();

    /**
     * 与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    private Session session;
    /**
     * 接收摄像头
     */
    private String cameraId = "";

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(final String message, final Session session) {
        log.info("服务端收到客户端[{}]的消息:{}", session.getId(), message);
    }

    @OnError
    public void onError(final Session session, final Throwable error) {
        log.error("发生错误", error);
        error.printStackTrace();
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(final Session session) {
        // 在线数减1
        onlineCount.decrementAndGet();
        log.info("有一连接关闭：{}，当前在线人数为：{}", session.getId(), onlineCount.get());
        videoStreamWebSocketSet.remove(this);
    }

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("cameraId") String cameraId) {
        this.session = session;
        this.cameraId = cameraId;
        // 在线数加1
        onlineCount.incrementAndGet();
        log.info("有新连接加入:{}，当前在线人数为：{}", session.getId(), onlineCount.get());
        videoStreamWebSocketSet.add(this);
        try {
            if (!DvrVideoManage.startPreviewStream(cameraId)) {
                session.close();
            }
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 实现服务器主动推送
     */
    private void sendByteBuffer(ByteBuffer message) throws IOException {
        this.session.getBasicRemote().sendBinary(message);
    }

    /**
     * 群发自定义消息
     */
    public static void sendInfo(String cameraId, byte[] bytes) {
        ByteBuffer byteBuf = ByteBuffer.wrap(bytes);
        if(videoStreamWebSocketSet.size()>0){
            for (VideoStreamWebSocket item : videoStreamWebSocketSet) {
                try {
                    if (item.cameraId.equals(cameraId)) {
                        item.sendByteBuffer(byteBuf);
                    }
                } catch (IOException ignored) {
                    // 发送失败关闭连接，并清除
                    try {
                        item.session.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    videoStreamWebSocketSet.remove(item);
                }
            }
        }else{
            DvrVideoManage.stopPreviewStream(cameraId);
        }
    }

}
